import type { StateTree } from "@pinia/nuxt/dist/runtime/composables";

export const persist = () => {
  return (
    process.client && {
      storage: localStorage,
      serializer: {
        serialize(value: StateTree) {
          const result = {} as any;
          IterationObject(value, (key: string, value: any) => {
            let res;
            const type = Object.prototype.toString.call(value);
            const serializeMap: Record<string, Function> = {
              "[object Map]": (val: Map<any, any>) => {
                return MapToKeyArray(val);
              },
            };
            res = serializeMap[type]?.(value);
            result[key] = { type, value: res ?? value };
          });
          return JSON.stringify(result);
        },
        deserialize(value: string) {
          const result = {} as any;
          const json = JSON.parse(value);
          IterationObject(json, (key: string) => {
            const { type, value: val } = json[key];
            const deserializeMap: Record<string, Function> = {
              "[object Map]": (val: any[]) => {
                return new Map(val);
              },
            };
            result[key] = deserializeMap[type]?.(val) ?? val;
          });
          return result;
        },
      },
    }
  );
};
